package com.bluetrum.abmate.leaudio;

import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bluetrum.abmate.R;
import com.bluetrum.abmate.databinding.LeAudioBisItemBinding;
import com.bluetrum.devicemanager.models.LeAudioBisItem;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class LeAudioBisAdapter extends RecyclerView.Adapter<LeAudioBisAdapter.ViewHolder> {

    private final List<Pair<Date, LeAudioBisItem>> items = new ArrayList<>();

    private final Handler timeoutHandler;
    private final Runnable timeoutRunnable = this::handleTimeout;
    private final static long TIMEOUT = 10000;
    private Date lastRefreshDate = new Date();

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(@NonNull final OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    public LeAudioBisAdapter() {
        timeoutHandler = new Handler(Looper.getMainLooper());
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
        LeAudioBisItemBinding binding = LeAudioBisItemBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Date lastUpdateDate = items.get(position).first;
        final LeAudioBisItem item = items.get(position).second;

        holder.broadcastName.setText(item.getBroadcastName());
        holder.programInfo.setText(item.getProgramInfo());
        holder.identifier.setText(String.format(Locale.getDefault(), "%d", item.getIdentifier()));
        holder.address.setText(item.getBroadcastAddress());
        holder.rssi.setText(String.format(Locale.getDefault(), "%d", item.getRssi()));

        // 超时的项目使用灰色底
        boolean timedOut = lastRefreshDate.getTime() - lastUpdateDate.getTime() > TIMEOUT;
        holder.container.setBackgroundColor(timedOut ? Color.LTGRAY : Color.WHITE);

        // 如果已经连接，则一直显示按键，否则根据是否超时决定是否显示
        if (Boolean.TRUE.equals(item.isConnected())) {
            holder.actionButton.setText(R.string.function_le_audio_bis_action_disconnect);
            holder.actionButton.setVisibility(View.VISIBLE);
        } else {
            holder.actionButton.setText(R.string.function_le_audio_bis_action_connect);
            holder.actionButton.setVisibility(timedOut ? View.GONE : View.VISIBLE);
        }

        // 连接状态
        holder.backgroundView.setBackgroundResource(
                Boolean.TRUE.equals(item.isConnected()) ? R.drawable.background_connected : R.drawable.background_disconnected
        );
    }

    public synchronized void updateList(List<Pair<Date, LeAudioBisItem>> list) {
        // 每次更新全部列表，不做增量处理
        this.items.clear();
        this.items.addAll(list);
        notifyDataSetChanged();
        // 更新最后时间
        lastRefreshDate = new Date();
        timeoutHandler.removeCallbacks(timeoutRunnable);
        timeoutHandler.postDelayed(timeoutRunnable, TIMEOUT);
    }

    public synchronized void removeAll() {
        timeoutHandler.removeCallbacks(timeoutRunnable);
        this.items.clear();
        notifyDataSetChanged();
    }

    @Override
    public long getItemId(final int position) {
        return position;
    }

    @Override
    public int getItemCount() {
        return items.size();
    }

    public boolean isEmpty() {
        return getItemCount() == 0;
    }

    private synchronized void handleTimeout() {
        lastRefreshDate = new Date();
        notifyDataSetChanged();
    }

    @FunctionalInterface
    public interface OnItemClickListener {
        void onItemClick(final View view, final LeAudioBisItem bisItem);
    }

    final class ViewHolder extends RecyclerView.ViewHolder {
        private final View backgroundView;
        private final View container;
        private final TextView broadcastName;
        private final TextView programInfo;
        private final TextView identifier;
        private final TextView address;
        private final TextView rssi;
        private final Button actionButton;

        private ViewHolder(final LeAudioBisItemBinding binding) {
            super(binding.getRoot());

            backgroundView = binding.backgroundView;
            container = binding.container;
            broadcastName = binding.broadcastName;
            programInfo = binding.programInfo;
            identifier = binding.identifier;
            address = binding.address;
            rssi = binding.rssi;
            actionButton = binding.actionButton;

            actionButton.setOnClickListener(view -> {
                if (mOnItemClickListener != null) {
                    int pos = getBindingAdapterPosition();
                    if(pos > -1) {
                        mOnItemClickListener.onItemClick(view, items.get(pos).second);
                    }
                }
            });
        }
    }
}
